package leetcode_601_700;

import java.util.HashMap;
import java.util.Map;

public class LeeCode_697 {
    public static void main(String[] args) {
        System.out.println(findShortestSubArray(new int[]{1, 2, 2, 3, 1, 4, 2}));
    }
    private static int findShortestSubArray(int[] nums) {
        Map<Integer, int[]> map = new HashMap<>();
        int ans = 10000000, max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])){
                map.get(nums[i])[0]++;
                map.get(nums[i])[2] = i;
            }else {
                map.put(nums[i], new int[]{1, i, i});
            }
            if (map.get(nums[i])[0] == max){
                ans = Math.min(ans, map.get(nums[i])[2] - map.get(nums[i])[1] + 1);
            }else if (map.get(nums[i])[0] > max){
                max = map.get(nums[i])[0];
                ans = map.get(nums[i])[2] - map.get(nums[i])[1] + 1;
            }
        }
        return ans;
    }
}
